<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!--     <script src="../node_modules/axios/dist/mine-axios.js"></script>-->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">axios取消请求</h2>
        <button class="btn btn-primary"> 发送请求 </button>
        <button class="btn btn-warning"> 取消请求 </button>
    </div>
    <script type="text/javascript">
        /* json-server命令：json-server --watch db.json --d 2000 */
        //构造函数
        function Axios(config) {
            this.config = config;
            this.interceptors = {
                request: new InterceptorManager(),
                response: new InterceptorManager(),
            }
        }

        Axios.prototype.request = function (config) {
            //创建一个promise对象
            let p = Promise.resolve(config);
            //创建一个数组
            const chain = [dispatchRequest, undefined];
            //处理拦截器
            //请求拦截器，将请求拦截器的回调压入chain的前面
            this.interceptors.request.handlers.forEach((item) => {
                chain.unshift(item.resolved, item.rejected);
            });
            //响应拦截器：从后面添加
            this.interceptors.response.handlers.forEach((item) => {
                chain.push(item.resolved, item.rejected);
            });
            while (chain.length > 0) {
                p = p.then(chain.shift(), chain.shift());
            }
            return dispatchRequest(config);
        }

        function dispatchRequest(config) {
            return xhrAdapter(config);
        }

        function xhrAdapter(config) {
            return new Promise((resolve, reject) => {
                var xhr = new XMLHttpRequest();
                xhr.open(config.method, config.url);
                // xhr.send();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            resolve({
                                // 配置对象
                                config: config,
                                // 响应体
                                data: xhr.response,
                                // 响应头
                                headers: xhr.getAllResponseHeaders(),
                                // xhr请求对象
                                request: xhr,
                                // 响应状态码
                                status: xhr.status,
                                // 响应状态字符串
                                statusText: xhr.statusText
                            });
                        } else {
                            reject(new Error(`请求失败，失败的状态码为${xhr.status}`));
                        }
                    }
                }
                xhr.send();
                //关于取消请求的处理
                if (config.cancelToken) {
                    config.cancelToken.promise.then((resp) => {
                        xhr.abort();
                    });
                }
            });
        }

        //创建实例
        let context = new Axios({});
        //创建axios函数
        let axios = Axios.prototype.request.bind(context);
        //将context属性config、interceptors添加至axios函数对象身上
        Object.keys(context).forEach((key) => {
            axios[key] = context[key];
        });
        // console.dir(axios);

        function CancelToken(executor) {
            let resolvePromise;
            this.promise = new Promise((resolve, reject) => {
                resolvePromise = resolve;
            });
            executor(() => {
                resolvePromise();
            });
        }

        //拦截器管理器的构造函数
        function InterceptorManager() {
            this.handlers = [];
        }

        InterceptorManager.prototype.use = function (resolved, rejected) {
            this.handlers.push({resolved, rejected});
        }

        let cancel = null;
        $(".btn-primary").click(function () {
            // 检测上一次请求是否已经完成
            if (cancel !== null) {
                // 如果已完成，则取消上一次的请求
                cancel();
            }
            axios({
                method: 'GET',
                url: 'http://localhost:3000/posts',
                cancelToken: new CancelToken((c) => {
                    cancel = c;
                })
            }).then(resp => {
                console.log(resp);
                //将cancel的值恢复初始化
                cancel = null;
            });
            return false;
        });

        $(".btn-warning").click(function () {
            cancel();
            return false;
        });
    </script>
</body>
</html>